package com.aloudmeta.grpc.server;

import com.aloudmeta.grpc.support.advice.GrpcAdvice;
import com.aloudmeta.grpc.support.advice.GrpcExceptionHandler;
import com.google.rpc.Code;
import com.google.rpc.ErrorInfo;
import com.google.rpc.Status;
import io.grpc.StatusRuntimeException;
import io.grpc.protobuf.StatusProto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.ComponentScan;

/**
 * huaixin 2022/1/28 10:17 AM
 */
@GrpcAdvice
@ComponentScan
public class DubboExceptionHandler {

    @GrpcExceptionHandler(IllegalArgumentException.class)
    public StatusRuntimeException handleResourceNotFoundException(IllegalArgumentException e) {
        //var errorMetaData = cause.getErrorMetaData();
        ErrorInfo errorInfo =
                ErrorInfo.newBuilder()
                        .setReason("Resource not found")
                        .setDomain("Product")
                        //.putAllMetadata(errorMetaData)
                        .build();

        String simpleName = e.getClass().getSimpleName();
        simpleName = StringUtils.substringBefore(simpleName, "Exception");
        String msg = "[" + simpleName + "]" + e.getMessage();
        Status status =
                com.google.rpc.Status.newBuilder()
                        .setCode(Code.INVALID_ARGUMENT.getNumber())
                        .setMessage(msg)
                        .build();
        return StatusProto.toStatusRuntimeException(status);
    }
}
